package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Override
    public PageResponse<RoleVo> findByPage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Role> page = (Page<Role>)roleMapper.findList(roleDto);
        return PageResponse.of(page,RoleVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRole(RoleDto roleDto) {
        // 先把DTO转成实体类
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);

        // 保存中间表的数据
        if (roleDto.getCheckedResourceNos()!=null) {

            // 先删除此角色之前的菜单资源数据
            roleResourceMapper.deleteByRoleId(role.getId());

            // List<RoleResource> resourceList = Arrays.stream(roleDto.getCheckedResourceNos()).map(resourceNo ->
            // {
            //     RoleResource roleResource = new RoleResource(role.getId(), resourceNo, "0");  //Long roleId, String resourceNo, String dataState
            //     return roleResource;
            // }).collect(Collectors.toList());

            String[] checkedResourceNos = roleDto.getCheckedResourceNos();
            List<RoleResource> resourceList = new ArrayList<>();
            for (String resourceNo : checkedResourceNos) {
                RoleResource roleResource = new RoleResource(role.getId(), resourceNo, "0");
                resourceList.add(roleResource);
            }

            if(CollUtil.isNotEmpty(resourceList)){
                roleResourceMapper.batchInsert(resourceList);
            }


        }

        return true;
    }

    @Override
    public Set<String> findResourcesByRoleId(Long roleId) {
        return roleResourceMapper.findResourcesByRoleId(roleId);
    }

    @Override
    public List<RoleVo> findAll() {
        List<Role> roleList = roleMapper.findList(new RoleDto());

        return BeanUtil.copyToList(roleList,RoleVo.class);
    }
}
